"""
添加任务对话框
"""
import re
import sys
import json
from pathlib import Path
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QPushButton,
                           QLineEdit, QLabel, QMessageBox, QFormLayout, QComboBox, QFrame, QWidget, QApplication)
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QIcon
from com.db.task_manager import TaskManager
from com.db.models import Task
from reqapi.get_template_info import GetTemplateInfoApi
from com.constants.wear_ranges import (WearCategory, get_wear_ranges, 
                                     get_category_by_wear, WEAR_CATEGORY_NAMES)
import logging
from datetime import datetime

logger = logging.getLogger(__name__)

class AddTaskDialog(QDialog):
    """添加任务对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.task_manager = TaskManager()
        self.item_id = None
        self.item_name = None
        self.item_price = None
        self.template_id = None
        self.item_info = None
        # 初始化状态变量，用于避免递归更新
        self.is_updating_profit_rate = False
        self.is_updating_scan_price = False
        self.setup_ui()
        
    def setup_ui(self):
        """初始化UI"""
        self.setWindowTitle("添加任务")
        self.setMinimumWidth(650)  # 原来是500，增加30%后变为650
        self.setMinimumHeight(400)  # 增加高度以容纳新增的元素
        self.setWindowModality(Qt.WindowModality.ApplicationModal)
        
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)
        
        # 表单布局
        form_layout = QFormLayout()
        form_layout.setSpacing(15)
        
        # UU饰品URL地址输入区域
        url_layout = QHBoxLayout()
        
        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("请输入UU饰品URL地址...")
        self.url_input.setMinimumWidth(300)
        self.url_input.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        
        self.load_btn = QPushButton("加载")
        self.load_btn.setStyleSheet("""
            QPushButton {
                background-color: #1890ff;
                border: none;
                border-radius: 4px;
                color: white;
                padding: 8px 15px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #096dd9;
            }
        """)
        self.load_btn.clicked.connect(self.on_load)
        
        url_layout.addWidget(self.url_input)
        url_layout.addWidget(self.load_btn)
        
        form_layout.addRow("UU饰品URL地址:", url_layout)
        
        # 饰品信息显示（统一在一个文本框中）
        self.item_info_text = QLabel("未加载")
        self.item_info_text.setStyleSheet("""
            QLabel {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                background-color: #f5f5f5;
                font-size: 14px;
                min-height: 120px;
            }
        """)
        self.item_info_text.setWordWrap(True)  # 允许文本换行
        self.item_info_text.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)  # 文本左上对齐
        form_layout.addRow("饰品信息:", self.item_info_text)
        
        # 添加状态选择下拉框
        self.status_combo = QComboBox()
        self.status_combo.addItem("启用", 1)
        self.status_combo.addItem("禁用", 0)
        self.status_combo.setCurrentIndex(0)  # 默认选择启用
        self.status_combo.setStyleSheet("""
            QComboBox {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QComboBox:hover {
                border-color: #40a9ff;
            }
        """)
        form_layout.addRow("状态:", self.status_combo)
        
        # 添加标签输入框
        self.tags_input = QLineEdit()
        self.tags_input.setPlaceholderText("请输入标签，多个标签用逗号分隔...")
        self.tags_input.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        form_layout.addRow("标签:", self.tags_input)
        
        # 添加购买数量输入框
        self.quantity_input = QLineEdit()
        self.quantity_input.setText("10")  # 默认为10
        self.quantity_input.setPlaceholderText("请输入购买数量...")
        self.quantity_input.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        form_layout.addRow("购买数量:", self.quantity_input)
        
        # 添加扫货定价类型下拉框
        self.pricing_type_combo = QComboBox()
        self.pricing_type_combo.addItem("固定价格", 0)
        self.pricing_type_combo.addItem("动态利润率", 1)
        self.pricing_type_combo.addItem("固定利润率", 2)
        self.pricing_type_combo.setCurrentIndex(1)  # 默认选择固定利润率
        self.pricing_type_combo.setStyleSheet("""
            QComboBox {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
                min-width: 150px;
            }
            QComboBox:hover {
                border-color: #40a9ff;
            }
        """)
        self.pricing_type_combo.currentIndexChanged.connect(self.on_pricing_type_changed)
        form_layout.addRow("扫货定价类型:", self.pricing_type_combo)
        
        # 创建价格框架布局
        price_frame = QFrame()
        price_frame.setFrameShape(QFrame.Shape.Box)
        price_frame.setFrameShadow(QFrame.Shadow.Sunken)
        price_frame.setStyleSheet("""
            QFrame {
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                background-color: #fafafa;
            }
        """)
        price_frame_layout = QVBoxLayout(price_frame)
        price_frame_layout.setContentsMargins(10, 10, 10, 10)
        price_frame_layout.setSpacing(10)
        
        # 固定价格输入框
        self.fixed_price_container = QWidget()
        fixed_price_layout = QHBoxLayout(self.fixed_price_container)
        fixed_price_layout.setContentsMargins(0, 0, 0, 0)
        fixed_price_label = QLabel("捡漏价：")
        fixed_price_label.setStyleSheet("font-size: 14px;")
        self.price_input = QLineEdit()
        self.price_input.setPlaceholderText("请输入捡漏价...")
        self.price_input.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        fixed_price_layout.addWidget(fixed_price_label)
        fixed_price_layout.addWidget(self.price_input)
        
        # 利润率输入框
        self.profit_rate_container = QWidget()
        profit_rate_layout = QHBoxLayout(self.profit_rate_container)
        profit_rate_layout.setContentsMargins(0, 0, 0, 0)
        profit_rate_label = QLabel("利润率：")
        profit_rate_label.setStyleSheet("font-size: 14px;")
        self.profit_rate_input = QLineEdit()
        self.profit_rate_input.setText("15.00")  # 默认为15%
        self.profit_rate_input.setPlaceholderText("请输入利润率...")
        self.profit_rate_input.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        percent_label = QLabel("%")
        percent_label.setStyleSheet("font-size: 14px;")
        profit_rate_layout.addWidget(profit_rate_label)
        profit_rate_layout.addWidget(self.profit_rate_input)
        profit_rate_layout.addWidget(percent_label)
        
        # 扫货价输入框
        self.scan_price_container = QWidget()
        scan_price_layout = QHBoxLayout(self.scan_price_container)
        scan_price_layout.setContentsMargins(0, 0, 0, 0)
        scan_price_label = QLabel("扫货价：")
        scan_price_label.setStyleSheet("font-size: 14px;")
        self.scan_price_input = QLineEdit()
        self.scan_price_input.setPlaceholderText("请输入扫货价...")
        self.scan_price_input.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        scan_price_layout.addWidget(scan_price_label)
        scan_price_layout.addWidget(self.scan_price_input)
        
        # 最低利润率输入框
        self.min_profit_rate_container = QWidget()
        min_profit_rate_layout = QHBoxLayout(self.min_profit_rate_container)
        min_profit_rate_layout.setContentsMargins(0, 0, 0, 0)
        min_profit_rate_label = QLabel("最低利润率：")
        min_profit_rate_label.setStyleSheet("font-size: 14px;")
        self.min_profit_rate_input = QLineEdit()
        self.min_profit_rate_input.setText("5.00")  # 默认为3%
        self.min_profit_rate_input.setPlaceholderText("请输入最低利润率...")
        self.min_profit_rate_input.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        min_percent_label = QLabel("%")
        min_percent_label.setStyleSheet("font-size: 14px;")
        min_profit_rate_layout.addWidget(min_profit_rate_label)
        min_profit_rate_layout.addWidget(self.min_profit_rate_input)
        min_profit_rate_layout.addWidget(min_percent_label)
        
        # 添加四个容器到价格框架中
        price_frame_layout.addWidget(self.fixed_price_container)
        price_frame_layout.addWidget(self.profit_rate_container)
        price_frame_layout.addWidget(self.scan_price_container)
        price_frame_layout.addWidget(self.min_profit_rate_container)
        
        # 初始化价格计算的状态变量
        self.is_updating_profit_rate = False
        self.is_updating_scan_price = False
        
        # 根据默认定价类型设置可见性
        self.fixed_price_container.setVisible(False)  # 默认隐藏固定价格
        self.profit_rate_container.setVisible(True)   # 默认显示利润率
        self.scan_price_container.setVisible(True)    # 默认显示扫货价
        self.min_profit_rate_container.setVisible(True)  # 默认显示最低利润率（因为默认是动态利润率）
        
        form_layout.addRow("", price_frame)
        
        # 添加磨损度选择下拉框
        self.wear_combo = QComboBox()
        self.wear_combo.setEnabled(False)  # 初始状态下禁用，需要先加载商品信息
        self.wear_combo.setStyleSheet("""
            QComboBox {
                padding: 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QComboBox:hover {
                border-color: #40a9ff;
            }
            QComboBox:disabled {
                background-color: #f5f5f5;
                color: #bfbfbf;
            }
        """)
        form_layout.addRow("磨损度:", self.wear_combo)
        
        layout.addLayout(form_layout)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)
        
        # 取消按钮
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.setStyleSheet("""
            QPushButton {
                background-color: #ffffff;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                color: #595959;
                padding: 8px 20px;
                font-size: 14px;
            }
            QPushButton:hover {
                border-color: #40a9ff;
                color: #40a9ff;
            }
            QPushButton:pressed {
                border-color: #096dd9;
                color: #096dd9;
            }
        """)
        self.cancel_btn.clicked.connect(self.reject)
        
        # 确认按钮
        self.confirm_btn = QPushButton("添加")
        self.confirm_btn.setStyleSheet("""
            QPushButton {
                background-color: #52c41a;
                border: none;
                border-radius: 4px;
                color: white;
                padding: 8px 20px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #73d13d;
            }
            QPushButton:pressed {
                background-color: #389e0d;
            }
        """)
        self.confirm_btn.clicked.connect(self.on_confirm)
        self.confirm_btn.setEnabled(False)  # 初始状态下禁用确认按钮
        
        button_layout.addStretch()
        button_layout.addWidget(self.cancel_btn)
        button_layout.addWidget(self.confirm_btn)
        
        layout.addStretch()
        layout.addLayout(button_layout)
        
        # 移除信号槽连接
        # self.profit_rate_input.textChanged.connect(self.on_profit_rate_changed)
        # self.scan_price_input.textChanged.connect(self.on_scan_price_changed)
    
    def on_pricing_type_changed(self, index):
        """扫货定价类型变更处理"""
        # 根据选择的定价类型显示/隐藏对应的输入框
        if index == 0:  # 固定价格
            self.fixed_price_container.setVisible(True)
            self.profit_rate_container.setVisible(False)
            self.scan_price_container.setVisible(False)
            self.min_profit_rate_container.setVisible(False)
        elif index == 1:  # 动态利润率
            self.fixed_price_container.setVisible(False)
            self.profit_rate_container.setVisible(True)
            self.scan_price_container.setVisible(True)
            self.min_profit_rate_container.setVisible(True)
        else:  # 固定利润率
            self.fixed_price_container.setVisible(False)
            self.profit_rate_container.setVisible(True)
            self.scan_price_container.setVisible(True)
            self.min_profit_rate_container.setVisible(False)
            
        # 如果已经加载了商品信息，计算并显示扫货价
        if self.item_price and self.item_price > 0:
            try:
                profit_rate_percent = float(self.profit_rate_input.text())
                if profit_rate_percent < 0:
                    profit_rate_percent = 0
                elif profit_rate_percent > 99:
                    profit_rate_percent = 99
                
                scan_price = self.item_price * (1 - profit_rate_percent/100)
                if scan_price <= 0:
                    scan_price = 0.01
                    
                self.scan_price_input.setText(f"{scan_price:.2f}")
            except ValueError:
                pass
    
    def on_load(self):
        """加载饰品信息"""
        url = self.url_input.text().strip()
        if not url:
            QMessageBox.warning(self, "警告", "请输入UU饰品URL地址")
            return
        
        # 从URL中提取templateId
        template_id = self.extract_template_id(url)
        if not template_id:
            QMessageBox.warning(self, "警告", "无法从URL中提取templateId，请检查URL格式")
            return
        
        try:
            # 保存templateId
            self.template_id = template_id
            
            # 获取商品信息
            self.item_info = self.get_item_info(template_id)
            if not self.item_info:
                QMessageBox.warning(self, "警告", "无法获取商品信息，请检查templateId是否正确")
                return
            
            # 更新UI显示
            self.item_id = str(template_id)
            self.item_name = self.item_info.CommodityName
            self.item_price = float(self.item_info.MinPrice)
            
            info_text = f"名称：{self.item_name}\n售价：¥{self.item_price:.2f}\n外观：{self.item_info.Exterior or '无'}\n稀有度：{self.item_info.Rarity or '无'}\n在售数量：{self.item_info.OnSaleCount}"
            self.item_info_text.setText(info_text)
            
            # 加载磨损度选择框
            self.load_wear_ranges()
            
            # 如果已选择利润率定价方式，计算并显示扫货价
            pricing_type = self.pricing_type_combo.currentData()
            if pricing_type != 0 and self.profit_rate_input.isEnabled():
                try:
                    profit_rate_percent = float(self.profit_rate_input.text())
                    scan_price = self.item_price * (1 - profit_rate_percent/100)
                    self.scan_price_input.setText(f"{scan_price:.2f}")
                except ValueError:
                    pass
            
            # 启用确认按钮
            self.confirm_btn.setEnabled(True)
            
        except Exception as e:
            logger.error(f"加载商品信息失败: {str(e)}")
            QMessageBox.warning(self, "错误", f"加载商品信息失败: {str(e)}")
    
    def load_wear_ranges(self):
        """加载磨损度选择框"""
        try:
            # 清空当前选项
            self.wear_combo.clear()
            
            # 获取当前外观类型
            exterior = self.item_info.Exterior if self.item_info else None
            if not exterior:
                self.wear_combo.setEnabled(False)
                return
                
            # 查找对应的外观类别
            category = None
            for cat in WearCategory:
                if WEAR_CATEGORY_NAMES[cat] == exterior:
                    category = cat
                    break
                    
            if not category:
                self.wear_combo.setEnabled(False)
                return
                
            # 获取该外观类型的磨损区间
            wear_ranges = get_wear_ranges(category)
            if not wear_ranges:
                self.wear_combo.setEnabled(False)
                return
                
            # 添加磨损区间到下拉框
            for wear_range in wear_ranges:
                self.wear_combo.addItem(wear_range.show_name, wear_range)
                
            # 启用磨损度选择框
            self.wear_combo.setEnabled(True)
            
        except Exception as e:
            logger.error(f"加载磨损区间失败: {str(e)}")
            self.wear_combo.setEnabled(False)
    
    def extract_template_id(self, url):
        """从URL中提取templateId"""
        # 示例URL: https://www.youpin898.com/market/goods-list?listType=10&templateId=108561&gameId=730
        pattern = r'templateId=(\d+)'
        match = re.search(pattern, url)
        if match:
            return match.group(1)
        return None
    
    def get_item_info(self, template_id):
        """获取商品信息
        
        调用get_template_info.py接口获取商品信息
        """
        try:
            # 从 scan_account_manager 获取随机有效账号
            from com.db.scan_account_manager import ScanAccountManager
            import random
            
            account_manager = ScanAccountManager()
            active_accounts = account_manager.get_active_accounts()
            
            if not active_accounts:
                logger.error("没有找到活跃的扫货账号")
                return None
            
            # 随机选择一个活跃账号
            account = random.choice(active_accounts)
            
            # 获取账号信息
            device_id = account.get('device_id')
            device_token = account.get('device_id')  # 通常device_token与device_id相同
            auth_token = f"Bearer {account.get('uu_token')}"
            uk = account.get('uk')
            
            if not all([device_id, auth_token, uk]):
                logger.error(f"账号信息不完整: {account}")
                return None
            
            # 创建API实例
            api = GetTemplateInfoApi(
                device_id=device_id,
                device_token=device_token,
                auth_token=auth_token,
                uk=uk
            )
            
            # 执行API请求
            response = api.execute(template_id=int(template_id))
            
            if response and response.TemplateInfo:
                return response.TemplateInfo
            else:
                logger.error("获取商品信息失败，API返回为空")
                return None
                
        except Exception as e:
            logger.error(f"API调用失败: {str(e)}")
            raise
    
    def on_profit_rate_changed(self):
        """处理利润率变化"""
        if self.item_price is not None and self.item_price > 0 and not self.is_updating_scan_price:
            try:
                # 获取输入文本
                text = self.profit_rate_input.text().strip()
                if not text:  # 如果文本为空，不执行计算
                    return
                    
                # 尝试将输入转换为浮点数
                profit_rate_percent = float(text)
                
                # 验证利润率合理性
                if profit_rate_percent < 0:
                    profit_rate_percent = 0
                elif profit_rate_percent > 99:
                    profit_rate_percent = 99
                
                # 计算方式: 扫货价 = (1-当前输入的利润率/100)*商品价格
                scan_price = self.item_price * (1 - profit_rate_percent/100)
                if scan_price <= 0:
                    scan_price = 0.01
                    
                print(f"利润率变化: {profit_rate_percent}% -> 扫货价: {scan_price}")
                
                # 避免递归更新
                self.is_updating_scan_price = True
                self.scan_price_input.setText(f"{scan_price:.2f}")
                self.is_updating_scan_price = False
            except ValueError:
                print(f"利润率输入无效: {self.profit_rate_input.text()}")
    
    def on_scan_price_changed(self):
        """处理扫货价变化"""
        if self.item_price is not None and self.item_price > 0 and not self.is_updating_profit_rate:
            try:
                # 获取输入文本
                text = self.scan_price_input.text().strip()
                if not text:  # 如果文本为空，不执行计算
                    return
                    
                # 尝试将输入转换为浮点数
                scan_price = float(text)
                
                # 验证扫货价合理性
                if scan_price <= 0:
                    scan_price = 0.01
                elif scan_price >= self.item_price:
                    scan_price = self.item_price * 0.99
                
                # 计算方式: 利润率 = (商品价格-当前输入的扫货价)/商品价格 * 100
                profit_rate_percent = (self.item_price - scan_price) / self.item_price * 100
                
                # 验证利润率合理性
                if profit_rate_percent < 0:
                    profit_rate_percent = 0
                elif profit_rate_percent > 99:
                    profit_rate_percent = 99
                
                print(f"扫货价变化: {scan_price} -> 利润率: {profit_rate_percent}%")
                
                # 避免递归更新
                self.is_updating_profit_rate = True
                self.profit_rate_input.setText(f"{profit_rate_percent:.2f}")
                self.is_updating_profit_rate = False
            except ValueError:
                print(f"扫货价输入无效: {self.scan_price_input.text()}")
                
    def keyPressEvent(self, event):
        """处理键盘事件"""
        # 检查是否按下回车键
        if event.key() == Qt.Key.Key_Return or event.key() == Qt.Key.Key_Enter:
            # 先获取当前焦点对象
            focus_widget = QApplication.focusWidget()
            
            # 根据焦点对象决定计算方向
            if focus_widget == self.profit_rate_input:
                self.on_profit_rate_changed()
                # 阻止事件传递，防止触发默认按钮
                event.accept()
                return
            elif focus_widget == self.scan_price_input:
                self.on_scan_price_changed()
                # 阻止事件传递，防止触发默认按钮
                event.accept()
                return
        
        # 其他情况继续传递事件给父类
        super().keyPressEvent(event)
    
    def on_confirm(self):
        """确认添加任务"""
        if not self.item_id or not self.item_name:
            QMessageBox.warning(self, "警告", "请先加载商品信息")
            return
        
        try:
            # 获取表单数据
            status = self.status_combo.currentData()
            
            # 处理标签
            tags_text = self.tags_input.text().strip()
            tags = [tag.strip() for tag in tags_text.split(',')] if tags_text else []
            
            # 获取购买数量
            try:
                buy_num_limit = int(self.quantity_input.text())
                if buy_num_limit <= 0:
                    QMessageBox.warning(self, "错误", "购买数量必须大于0")
                    return
            except ValueError:
                QMessageBox.warning(self, "错误", "请输入有效的购买数量")
                return
            
            # 获取扫货定价类型
            pricing_type = self.pricing_type_combo.currentData()
            
            # 获取利润率
            try:
                profit_rate_percent = float(self.profit_rate_input.text())
                if profit_rate_percent < 0 or profit_rate_percent > 99:
                    QMessageBox.warning(self, "错误", "利润率必须在0-99之间")
                    return
            except ValueError:
                QMessageBox.warning(self, "错误", "请输入有效的利润率")
                return
            
            # 获取最低利润率（仅当选择动态利润率时）
            min_profit_rate = None
            if pricing_type == 1:  # 动态利润率
                try:
                    min_profit_rate_text = self.min_profit_rate_input.text().strip()
                    if min_profit_rate_text:
                        min_profit_rate = float(min_profit_rate_text)  # 直接使用百分比值
                        # 确保最低利润率在合理范围内
                        if min_profit_rate < 0 or min_profit_rate > 99:
                            QMessageBox.warning(self, "错误", "最低利润率必须在0-99之间")
                            return
                except ValueError:
                    QMessageBox.warning(self, "错误", "请输入有效的最低利润率")
                    return
            
            # 获取扫货价
            try:
                buy_price_limit = float(self.scan_price_input.text()) if self.scan_price_input.text().strip() else self.item_price
                if buy_price_limit <= 0:
                    QMessageBox.warning(self, "错误", "扫货价必须大于0")
                    return
            except ValueError:
                QMessageBox.warning(self, "错误", "请输入有效的扫货价")
                return
            
            # 获取磨损度范围
            filter_conf = {}
            wear_value = None
            if self.wear_combo.isEnabled() and self.wear_combo.currentData():
                wear_range = self.wear_combo.currentData()
                filter_conf = {
                    "type": "paintwear",
                    "min_paintwear": f"{wear_range.min_val:.3f}",
                    "max_paintwear": f"{wear_range.max_val:.3f}"
                }
                # 设置wear字段格式
                wear_value = f"{wear_range.min_val:.3f}-{wear_range.max_val:.3f}"
            
            # 获取当前时间并格式化
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            
            # 检查是否已存在相同商品ID的任务
            existing_task = self.task_manager.get_task_by_goods_id(int(self.item_id))
            if existing_task:
                QMessageBox.warning(self, "提示", f"该饰品已存在任务: {existing_task.get('name')}")
                return
            
            # 创建新任务数据字典
            task_data = {
                'goods_id': int(self.item_id),  # 使用template_id作为goods_id
                'name': self.item_name,
                'sell_min_price': self.item_price,
                'target_sell_price': self.item_price,  # 设置为饰品的普通价格
                'profit_rate': profit_rate_percent,
                'min_profit_rate': min_profit_rate,  # 添加最低利润率
                'pricing_type': pricing_type,
                'status': status,
                'buy_num_limit': buy_num_limit,
                'bought_num': 0,
                'sell_num': self.item_info.OnSaleCount if self.item_info else 0,
                'hash_name': self.item_info.CommodityHashName if self.item_info else None,
                'wear': wear_value,
                'rarity': self.item_info.Rarity if self.item_info else None,
                'quality': self.item_info.Quality if self.item_info else None,
                'exterior': self.item_info.Exterior if self.item_info else None,
                'tags': json.dumps(tags),
                'goods_url': self.url_input.text().strip(),
                'filter_conf': json.dumps(filter_conf),
                'buy_price_limit': buy_price_limit,  # 设置为扫货价
                'min_interval': 10,  # 默认设置为10
                'create_at': current_time  # 设置为当前时间，格式为2025-03-19 15:52:17
            }
            
            # 保存到数据库
            task_id = self.task_manager.add_task(task_data)
            
            if task_id:
                QMessageBox.information(self, "成功", f"已成功添加任务: {self.item_name}")
                self.accept()  # 关闭对话框并返回接受状态
            else:
                QMessageBox.warning(self, "警告", "添加任务失败，可能是商品ID已存在")
                
        except Exception as e:
            logger.error(f"添加任务失败: {str(e)}")
            QMessageBox.warning(self, "错误", f"添加任务失败: {str(e)}")
